package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysMedicines;
import com.ruoyi.system.domain.vo.SysPrescriptionsVo;
import com.ruoyi.system.mapper.SysMedicinesMapper;
import com.ruoyi.system.service.ISysJashuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysPrescriptions;
import com.ruoyi.system.service.ISysPrescriptionsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 销售信息Controller
 * 
 * @author jiashu
 * @date 2025-03-13
 */
@RestController
@RequestMapping("/system/sale")
public class SysPrescriptionsController extends BaseController
{
    @Autowired
    private ISysPrescriptionsService sysPrescriptionsService;
    @Autowired
    private ISysJashuService sysJashuService;
    @Autowired
    private SysMedicinesMapper sysMedicinesMapper;

    /**
     * 查询销售信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:sale:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysPrescriptions sysPrescriptions)
    {
        startPage();
        sysPrescriptions = sysJashuService.getSysPrescriptionsSelectParam(sysPrescriptions);
        List<SysPrescriptions> list = sysPrescriptionsService.selectSysPrescriptionsList(sysPrescriptions);
        return getDataTable(sysJashuService.getSysPrescriptionsVoList(list));
    }

    /**
     * 导出销售信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:sale:export')")
    @Log(title = "销售信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPrescriptions sysPrescriptions)
    {
        List<SysPrescriptions> list = sysPrescriptionsService.selectSysPrescriptionsList(sysPrescriptions);
        ExcelUtil<SysPrescriptions> util = new ExcelUtil<SysPrescriptions>(SysPrescriptions.class);
        util.exportExcel(response, list, "销售信息数据");
    }

    /**
     * 获取销售信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sale:query')")
    @GetMapping(value = "/{prescriptionId}")
    public AjaxResult getInfo(@PathVariable("prescriptionId") Long prescriptionId)
    {
        return success(sysPrescriptionsService.selectSysPrescriptionsByPrescriptionId(prescriptionId));
    }

    /**
     * 新增销售信息
     */
    @PreAuthorize("@ss.hasPermi('system:sale:add')")
    @Log(title = "销售信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysPrescriptions sysPrescriptions)
    {
        sysPrescriptions.setCreateBy(getUsername());
        sysPrescriptions.setCreateTime(DateUtils.getNowDate());
        sysPrescriptions.setDoctorId(getUserId());//医生id为登录用户id
        // 新增销售信息时要判断库存量是否足够

        Long medicineId = sysPrescriptions.getMedicineId();

        SysMedicines sysMedicines = sysMedicinesMapper.selectSysMedicinesByMedicineId(medicineId);
        // 库存总数
        Double stockQuantity = sysMedicines.getStockQuantity();
        SysPrescriptions usedMedicine = new SysPrescriptions();
        usedMedicine.setMedicineId(medicineId);
        usedMedicine.setIsArchived("0");

        List<SysPrescriptions> sysPrescriptions1 = sysPrescriptionsService.selectSysPrescriptionsList(usedMedicine);
        Double usedNumber = 0.0;
        for (SysPrescriptions prescriptions : sysPrescriptions1) {
            Double quantityPrescribed = prescriptions.getQuantityPrescribed();
            usedNumber +=quantityPrescribed;
        }

        // 剩余库存
        Double quantityPrescribed = sysPrescriptions.getQuantityPrescribed();
        Double remaining=stockQuantity-usedNumber;
        // 如果剩余库存小于使用量则无法添加
        if(remaining<quantityPrescribed){
            return error("该药品库存量不足当前药品库存："+remaining);
        }

        return toAjax(sysPrescriptionsService.insertSysPrescriptions(sysPrescriptions));
    }

    /**
     * 修改销售信息
     */
    @PreAuthorize("@ss.hasPermi('system:sale:edit')")
    @Log(title = "销售信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysPrescriptions sysPrescriptions)
    {
        Long prescriptionId = sysPrescriptions.getPrescriptionId();
        SysPrescriptions sysPrescriptions1 = sysPrescriptionsService.selectSysPrescriptionsByPrescriptionId(prescriptionId);
        if("1".equals(sysPrescriptions1.getIsArchived())){
            // 如果已归档不允许修改
            return AjaxResult.error("已归档的销售信息不允许修改");
        }

        Long medicineId = sysPrescriptions.getMedicineId();



        SysMedicines sysMedicines = sysMedicinesMapper.selectSysMedicinesByMedicineId(medicineId);
        // 库存总数
        Double stockQuantity = sysMedicines.getStockQuantity();
        SysPrescriptions usedMedicine = new SysPrescriptions();
        usedMedicine.setMedicineId(medicineId);
        usedMedicine.setIsArchived("0");

        List<SysPrescriptions> sysPrescriptionsList = sysPrescriptionsService.selectSysPrescriptionsList(usedMedicine);
        Double usedNumber = 0.0;
        for (SysPrescriptions prescriptions : sysPrescriptionsList) {
            if(prescriptions.getPrescriptionId().equals(sysPrescriptions.getPrescriptionId())){
                continue;
            }
            Double quantityPrescribed = prescriptions.getQuantityPrescribed();
            usedNumber +=quantityPrescribed;
        }

        // 剩余库存
        Double quantityPrescribed = sysPrescriptions.getQuantityPrescribed();
        Double remaining=stockQuantity-usedNumber;
        // 如果剩余库存小于使用量则无法添加
        if(remaining<quantityPrescribed){
            return error("该药品库存量不足当前药品库存："+remaining);
        }
        sysPrescriptions.setUpdateBy(getUsername());
        sysPrescriptions.setUpdateTime(DateUtils.getNowDate());
        sysPrescriptions.setDoctorId(getUserId());//医生id为登录用户id
        return toAjax(sysPrescriptionsService.updateSysPrescriptions(sysPrescriptions));
    }

    @PreAuthorize("@ss.hasPermi('system:sale:archived')")
    @Log(title = "归档", businessType = BusinessType.UPDATE)
    @PostMapping("/archived/{sysPrescriptionsId}")
    public AjaxResult archived(@PathVariable Long sysPrescriptionsId)
    {
        SysPrescriptions sysPrescriptions = sysPrescriptionsService.selectSysPrescriptionsByPrescriptionId(sysPrescriptionsId);
        if("1".equals(sysPrescriptions.getIsArchived())){
            // 如果已归档不允许修改
            return AjaxResult.error("已归档不需要再归档");
        }
        sysPrescriptions.setUpdateBy(getUsername());
        sysPrescriptions.setUpdateTime(DateUtils.getNowDate());
        return toAjax(sysPrescriptionsService.archivedPrescriptions(sysPrescriptions));
    }
    /**
     * 删除销售信息
     */
    @PreAuthorize("@ss.hasPermi('system:sale:remove')")
    @Log(title = "销售信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{prescriptionIds}")
    public AjaxResult remove(@PathVariable Long[] prescriptionIds)
    {
        // 已归档的不允许删除
        List<SysPrescriptions> list = new ArrayList<>();

        for (Long prescriptionId : prescriptionIds) {
            SysPrescriptions sysPrescriptions = sysPrescriptionsService.selectSysPrescriptionsByPrescriptionId(prescriptionId);
            if("0".equals(sysPrescriptions.getIsArchived())){
                list.add(sysPrescriptions);
            }
        }
        Long[] param = new Long[list.size()];

        for (int i = 0; i < list.size(); i++) {
            param[i] = list.get(i).getPrescriptionId();
        }
        if (list.isEmpty()) {
            return warn("已归档信息不允许删除");
        }
        return toAjax(sysPrescriptionsService.deleteSysPrescriptionsByPrescriptionIds(param));
    }
}
